import { Client } from "@stomp/stompjs";

let stompClient = null;
let chatHandlers = [];
let notificationHandlers = [];
let connectionStatusHandlers = [];

// 连接状态
let isConnected = false;

// 重连配置
const RECONNECT_DELAY = 5000; // 5秒
const MAX_RECONNECT_ATTEMPTS = 5;
let reconnectAttempts = 0;

// 修改 WebSocket 配置，确保订阅路径正确
export const connectWebSocket = (userId) => {
  if (stompClient && stompClient.connected) {
    console.log("WebSocket 已经连接");
    return;
  }

  stompClient = new Client({
    brokerURL: "ws://localhost:8080/ws",
    connectHeaders: {
      userId: userId.toString(),
    },
    debug: (str) => {
      console.log("STOMP Debug:", str);
    },
    reconnectDelay: RECONNECT_DELAY,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,
    onConnect: () => {
      console.log("WebSocket 连接成功");
      isConnected = true;
      reconnectAttempts = 0;
      updateConnectionStatus(true);

      // 订阅通知
      stompClient.subscribe(`/user/${userId}/topic/notification`, (message) => {
        try {
          let notification;
          try {
            // 尝试解析为JSON
            notification = JSON.parse(message.body);
          } catch (e) {
            // 如果不是JSON，则创建一个简单的通知对象
            notification = {
              message: message.body,
              type: 'text'
            };
          }
          console.log("收到通知:", notification);
          notificationHandlers.forEach((handler) => handler(notification));
        } catch (error) {
          console.error("处理通知消息失败:", error);
        }
      });

      // 订阅聊天消息
      stompClient.subscribe(`/user/${userId}/queue/messages`, (message) => {
        try {
          const chatMessage = JSON.parse(message.body);
          console.log("收到聊天消息:", chatMessage);
          chatHandlers.forEach((handler) => handler(chatMessage));
        } catch (error) {
          console.error("处理聊天消息失败:", error);
        }
      });
    },
    onDisconnect: () => {
      console.log("WebSocket 连接关闭");
      isConnected = false;
      updateConnectionStatus(false);

      // 尝试重连
      if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
        reconnectAttempts++;
        console.log(`尝试重连 (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})...`);
        setTimeout(() => {
          if (!isConnected) {
            stompClient.activate();
          }
        }, RECONNECT_DELAY);
      } else {
        console.error("达到最大重连次数，请刷新页面重试");
        updateConnectionStatus(false, "连接失败，请刷新页面重试");
      }
    },
    onStompError: (frame) => {
      console.error("STOMP 错误:", frame);
      updateConnectionStatus(false, "连接错误");
    },
  });

  stompClient.activate();
};

// 断开 WebSocket 连接
export const disconnectWebSocket = () => {
  if (stompClient && stompClient.connected) {
    stompClient.deactivate();
    console.log("WebSocket 连接已断开");
  }
};

// 更新连接状态并通知监听器
const updateConnectionStatus = (isConnected, errorMessage = null) => {
  connectionStatusHandlers.forEach((handler) => handler(isConnected, errorMessage));
};

// 发送聊天消息
export const sendChatMessage = (message) => {
  if (!stompClient || !stompClient.connected) {
    console.error("WebSocket 未连接，无法发送消息");
    return false;
  }

  try {
    console.log("发送消息:", message);
    stompClient.publish({
      destination: "/app/chat.sendMessage",
      body: JSON.stringify(message),
    });
    return true;
  } catch (error) {
    console.error("发送消息失败:", error);
    return false;
  }
};

// 发送视频通话请求
export const sendVideoOffer = (message) => {
  if (!stompClient || !stompClient.connected) {
    console.error("WebSocket 未连接，无法发送视频通话请求");
    return false;
  }

  try {
    console.log("发送视频通话请求:", message);
    stompClient.publish({
      destination: "/app/chat.videoOffer",
      body: JSON.stringify(message),
    });
    return true;
  } catch (error) {
    console.error("发送视频通话请求失败:", error);
    return false;
  }
};

// 发送视频通话应答
export const sendVideoAnswer = (message) => {
  if (!stompClient || !stompClient.connected) {
    console.error("WebSocket 未连接，无法发送视频通话应答");
    return false;
  }

  try {
    console.log("发送视频通话应答:", message);
    stompClient.publish({
      destination: "/app/chat.videoAnswer",
      body: JSON.stringify(message),
    });
    return true;
  } catch (error) {
    console.error("发送视频通话应答失败:", error);
    return false;
  }
};

// 发送ICE候选者信息
export const sendIceCandidate = (message) => {
  if (!stompClient || !stompClient.connected) {
    console.error("WebSocket 未连接，无法发送ICE候选者信息");
    return false;
  }

  try {
    console.log("发送ICE候选者信息:", message);
    stompClient.publish({
      destination: "/app/chat.iceCandidate",
      body: JSON.stringify(message),
    });
    return true;
  } catch (error) {
    console.error("发送ICE候选者信息失败:", error);
    return false;
  }
};

// 发送挂断视频通话请求
export const sendVideoHangup = (message) => {
  if (!stompClient || !stompClient.connected) {
    console.error("WebSocket 未连接，无法发送挂断视频通话请求");
    return false;
  }

  try {
    console.log("发送挂断视频通话请求:", message);
    stompClient.publish({
      destination: "/app/chat.videoHangup",
      body: JSON.stringify(message),
    });
    return true;
  } catch (error) {
    console.error("发送挂断视频通话请求失败:", error);
    return false;
  }
};

// 监听聊天消息
export const addChatListener = (callback) => {
  if (!chatHandlers.includes(callback)) {
    chatHandlers.push(callback);
  }
};

// 移除聊天监听
export const removeChatListener = (callback) => {
  chatHandlers = chatHandlers.filter((handler) => handler !== callback);
};

// 监听通知
export const addNotificationListener = (callback) => {
  if (!notificationHandlers.includes(callback)) {
    notificationHandlers.push(callback);
  }
};

// 移除通知监听
export const removeNotificationListener = (callback) => {
  notificationHandlers = notificationHandlers.filter((handler) => handler !== callback);
};

// 监听连接状态
export const addConnectionStatusListener = (callback) => {
  if (!connectionStatusHandlers.includes(callback)) {
    connectionStatusHandlers.push(callback);
  }
};

// 移除连接状态监听
export const removeConnectionStatusListener = (callback) => {
  connectionStatusHandlers = connectionStatusHandlers.filter((handler) => handler !== callback);
};

// 清理所有监听器
export const clearAllListeners = () => {
  chatHandlers = [];
  notificationHandlers = [];
  connectionStatusHandlers = [];
};
